﻿#include "CInfoExchangeBase.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDateTime>
#include <QTextCodec>
#include <QTimer>
#include <QEventLoop>
#include <QThread>
#include <QDebug>

CInfoExchangeBase::CInfoExchangeBase(QObject *parent) : QObject(parent), QRunnable()
{
	qRegisterMetaType<SReqDataParam>("SReqDataParam");
	qRegisterMetaType<SRspDataParam>("SRspDataParam");
	setAutoDelete(true);//放到线程池之后，工作完自动析构(任务执行完毕,该对象自动销毁)
	initData();
}

CInfoExchangeBase::~CInfoExchangeBase()
{

}

//线程工作方法
void CInfoExchangeBase::run()
{
	m_locker.lock();
	handleReqQueue();
	m_locker.unlock();
}

//获取请求数据
void CInfoExchangeBase::getReqString(QString sReqString, SReqDataParam & stParam)
{
	// 将JSON字符串转换为QJsonDocument
	QJsonDocument jsonDocument = QJsonDocument::fromJson(sReqString.toUtf8());

	// 检查JSON文档是否有效
	if (!jsonDocument.isNull())
	{
		// 检查JSON文档的根是否为对象
		if (jsonDocument.isObject())
		{
			// 从JSON文档中获取根对象
			QJsonObject jsonObject = jsonDocument.object();

			//解析设备Guid
			if (jsonObject.contains("reqGuid"))
			{
				stParam.sReqGuid = jsonObject["reqGuid"].toString();
			}

			//解析命令代码
			if (jsonObject.contains("cmd"))
			{
				stParam.nCmd = jsonObject["cmd"].toInt();
			}

			//解析参数
			if (jsonObject.contains("param"))
			{
				QJsonObject qParamJson = jsonObject["param"].toObject();
				QJsonDocument qRspJsonDocument;
				qRspJsonDocument.setObject(qParamJson);
				QByteArray qRspJsonByteArray = qRspJsonDocument.toJson(QJsonDocument::Compact);
				stParam.sParam = QString(qRspJsonByteArray);
			}

			//解析协议类型
			if (jsonObject.contains("reqType"))
			{
				stParam.nReqType = jsonObject["reqType"].toInt();
			}

			//解析发送时间
			if (jsonObject.contains("sendTime"))
			{
				stParam.sSendTime = jsonObject["sendTime"].toString();
			}
		}
	}
}

//添加接收消息到队列中
void CInfoExchangeBase::addReqToQueue(SReqDataParam stParam)
{
	emit sigAddReqToQueue(stParam);
}

//解析响应信息添加接收消息到队列中
void CInfoExchangeBase::analyzeReqStringToQueue(QString sReqString)
{
	emit sigAnalyzeReqStringToQueue(sReqString);
}

void CInfoExchangeBase::initData()
{
	m_bIsStop = false;
	connect(this, &CInfoExchangeBase::sigAddReqToQueue, this, &CInfoExchangeBase::slotAddReqToQueue);
	connect(this, &CInfoExchangeBase::sigAnalyzeReqStringToQueue, this, &CInfoExchangeBase::slotAnalyzeReqStringToQueue);
}

//处理请求队列
void CInfoExchangeBase::handleReqQueue()
{
	//队列为空 直接返回
	if (m_qReqQueue.isEmpty())
	{
		return;
	}

	/*执行头部的队列任务*/
	SReqDataParam stReqData = m_qReqQueue.dequeue();
	analyzeReqData(stReqData);

	QEventLoop loop;
	QTimer::singleShot(100, &loop, SLOT(quit()));
	loop.exec();
}

//解析请求信息
void CInfoExchangeBase::analyzeReqData(SReqDataParam stParam)
{
	/*先判断是控制协议还是报文协议*/
	EProtType enType = static_cast<EProtType>(stParam.nReqType);
	switch (enType)
	{
	case enCtrProt:     //控制协议
		handleCtrProt(stParam);
		break;
	case enMsgProt:     //报文推送协议
		handleMsgProt(stParam);
		break;
	default:
		SRspDataParam stRspData;
		createRspMsg(stRspData, stParam, 500, QString::fromLocal8Bit("未知协议类型! ") + QString::number(stParam.nReqType), "");
		emit sigSendRspMsg(stRspData);
		QString sRspMsgString;
		createRspMsgString(stRspData, sRspMsgString);
		emit sigSendRspMsgString(sRspMsgString);
		break;
	}
}

//创建响应数据
void CInfoExchangeBase::createRspMsg(SRspDataParam & stRspParam, SReqDataParam stReqParam, int nSatus, QString sMsg, QString sRspParam)
{
	stRspParam.sRspGuid = stReqParam.sReqGuid;
	stRspParam.nCmd = stReqParam.nCmd;
	stRspParam.nRspType = stReqParam.nReqType;
	stRspParam.nStatus = nSatus;
	stRspParam.sMsg = sMsg;
	stRspParam.sRspParam = sRspParam;
	stRspParam.sRspime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
}

//创建响应数据字符串
void CInfoExchangeBase::createRspMsgString(SRspDataParam stRspParam, QString & sRspParamString)
{
	QJsonObject qRspJson;
	qRspJson.insert("rspGuid", stRspParam.sRspGuid);
	qRspJson.insert("sceneType", stRspParam.sSceneType);
	qRspJson.insert("cmd", stRspParam.nCmd);
	qRspJson.insert("rspType", stRspParam.nRspType);
	qRspJson.insert("rspWay", stRspParam.nRspWay);
	qRspJson.insert("status", stRspParam.nStatus);
	qRspJson.insert("msg", stRspParam.sMsg);

	QTextCodec *pTc = QTextCodec::codecForName("UTF-8");//防止中文乱码
	QJsonDocument qRspParamDoc = QJsonDocument::fromJson(stRspParam.sRspParam.toUtf8().data());
	if (qRspParamDoc.isArray())
	{
		qRspJson.insert("rspParam", qRspParamDoc.array());
	}
	else if (qRspParamDoc.isObject())
	{
		qRspJson.insert("rspParam", qRspParamDoc.object());
	}
	else
	{
		qRspJson.insert("rspParam", "");
	}

	qRspJson.insert("rspTime", QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

	QJsonDocument qRspJsonDocument;
	qRspJsonDocument.setObject(qRspJson);
	QByteArray qRspJsonByteArray = qRspJsonDocument.toJson(QJsonDocument::Compact);
	sRspParamString = QString(qRspJsonByteArray);
}

//添加接收消息到队列中
void CInfoExchangeBase::slotAddReqToQueue(SReqDataParam stParam)
{
	m_locker.lock();
	m_qReqQueue.enqueue(stParam);
	m_locker.unlock();
}

//解析响应信息添加接收消息到队列中
void CInfoExchangeBase::slotAnalyzeReqStringToQueue(QString sReqString)
{
	// 将JSON字符串转换为QJsonDocument
	QJsonDocument jsonDocument = QJsonDocument::fromJson(sReqString.toUtf8());
	// 将数据导入
	SReqDataParam stParam;

	// 检查JSON文档是否有效
	if (!jsonDocument.isNull())
	{
		// 检查JSON文档的根是否为对象
		if (jsonDocument.isObject())
		{
			// 从JSON文档中获取根对象
			QJsonObject jsonObject = jsonDocument.object();
			bool bAnalyseRet = true;       //解析结果

			//解析设备Guid
			if (jsonObject.contains("reqGuid"))
			{
				stParam.sReqGuid = jsonObject["reqGuid"].toString();
			}
			else
			{
				bAnalyseRet = false;
			}
			//解析命令代码
			if (jsonObject.contains("cmd"))
			{
				stParam.nCmd = jsonObject["cmd"].toInt();
			}
			else
			{
				bAnalyseRet = false;
			}
			//解析参数
			if (jsonObject.contains("param"))
			{
				QJsonObject qParamJson = jsonObject["param"].toObject();
				QJsonDocument qRspJsonDocument;
				qRspJsonDocument.setObject(qParamJson);
				QByteArray qRspJsonByteArray = qRspJsonDocument.toJson(QJsonDocument::Compact);
				stParam.sParam = QString(qRspJsonByteArray);
			}
			else
			{
				bAnalyseRet = false;
			}
			//解析协议类型
			if (jsonObject.contains("reqType"))
			{
				stParam.nReqType = jsonObject["reqType"].toInt();
			}
			else
			{
				bAnalyseRet = false;
			}
			//解析协议类型
			if (jsonObject.contains("reqWay"))
			{
				stParam.nReqWay = jsonObject["reqWay"].toInt();
			}
			else
			{
				bAnalyseRet = false;
			}
			//请求场景类型
			if (jsonObject.contains("sceneType"))
			{
				stParam.sSceneType = jsonObject["sceneType"].toString();
			}
			else
			{
				stParam.sSceneType = "rob";//默认是机器人场景
			}
			//解析发送时间
			if (jsonObject.contains("sendTime"))
			{
				stParam.sSendTime = jsonObject["sendTime"].toString();
			}
			else
			{
				bAnalyseRet = false;
			}

			//返回错误消息
			if (false == bAnalyseRet)
			{
				SRspDataParam stRspData;
				createRspMsg(stRspData, stParam, 500, QString::fromLocal8Bit("报文内容有空缺!"), "");
				emit sigSendRspMsg(stRspData);
				QString sRspMsgString;
				createRspMsgString(stRspData, sRspMsgString);
				emit sigSendRspMsgString(sRspMsgString);
			}
			//加入队列
			else
			{
				m_locker.lock();
				m_qReqQueue.enqueue(stParam);
				m_locker.unlock();
			}
		}
	}
	else
	{
		//发送解析失败的消息
		SRspDataParam stRspData;
		createRspMsg(stRspData, stParam, 500, QString::fromLocal8Bit("报文内容解析失败!"), "");
		emit sigSendRspMsg(stRspData);
		QString sRspMsgString;
		createRspMsgString(stRspData, sRspMsgString);
		emit sigSendRspMsgString(sRspMsgString);
	}
}
